import React, { Component } from 'react'
import { BrowserRouter, Switch, Route, Redirect } from 'react-router-dom'
import { Provider } from 'react-redux'
import store from 'src/store'
import { actionCreators as appActionCreators } from './store/app'
import { getUserIng } from 'common/js/util'
import Login from 'components/Login/loadable'
import Home from 'components/Home/loadable'

// 路由拦截
const PrivateRouter = ({ component: Component, ...rest }) => {
  const User = getUserIng()
  return (
    <Route
      {...rest}
      render={(props) => (
        User ? (
          <Component {...props} />
        ) : (
          <Redirect to="/" />
        )
      )}
    />
  )
}

class App extends Component {
  componentWillMount () {
    this.initUser()
  }

  componentDidMount () {
    this.bindResize()
  }

  render() {
    return (
      <Provider store={store}>
        <BrowserRouter>
          <div className="App">
            <Switch>
              <Route exact path="/" component={Login} />
              <PrivateRouter path="/home" component={Home} />
              <Redirect to="/" />
            </Switch>
          </div>
        </BrowserRouter>
      </Provider>
    )
  }

  initUser () {
    const User = getUserIng()

    if (User) {
      store.dispatch(appActionCreators.changeUserInfoAction(User))
    }
  }

  bindResize () {
    store.dispatch(appActionCreators.changeBodySizeAction())

    window.onresize = () => {
      store.dispatch(appActionCreators.changeBodySizeAction())
    }
  }
}

export default App
